package com.lap.auth.application.dict;

import com.lap.auth.application.dict.assembler.DictTypeAssembler;
import com.lap.auth.application.dict.command.CreateDictTypeCmd;
import com.lap.auth.application.dict.command.UpdateDictTypeCmd;
import com.lap.auth.domain.dict.DictType;
import com.lap.auth.domain.dict.repository.DictRepository;
import com.lap.auth.domain.dict.repository.DictTypeRepository;
import com.lap.auth.domain.dict.service.DictTypeValidator;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@RequiredArgsConstructor
@Service
public class DictTypeAppService {

  private final DictTypeAssembler dictTypeAssembler;
  private final DictTypeValidator dictTypeValidator;
  private final DictTypeRepository dictTypeRepository;
  private final DictRepository dictRepository;

  @Transactional(rollbackFor = Exception.class)
  public Integer createDictType(CreateDictTypeCmd cmd) {
    dictTypeValidator.validateCodeUnique(cmd.getCode());

    DictType dictType = dictTypeAssembler.toDomain(cmd);

    if (!dictType.getDictList().isEmpty()) {
      dictRepository.saveAll(dictType.getDictList());
    }
    return dictTypeRepository.save(dictType);
  }

  public Integer updateDictType(Integer id, UpdateDictTypeCmd cmd) {
    DictType dictType = dictTypeValidator.assertDictTypeExists(id);
    dictType.changeInfo(cmd.getModule(), cmd.getName(), cmd.getRemark());
    return dictTypeRepository.save(dictType);
  }

  @Transactional(rollbackFor = Exception.class)
  public Integer deleteDictType(Integer id) {
    DictType dictType = dictTypeValidator.assertDictTypeExists(id);
    dictRepository.deleteByDictTypeCode(dictType.getCode());
    return dictTypeRepository.deleteById(id);
  }
}
